package com.khtec.tools.parsetool.common;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * 格式化工具类，用于美化JSON和XML字符串
 */
public class FormatUtil {

    /**
     * 美化JSON字符串，添加缩进和换行
     *
     * @param jsonStr 原始JSON字符串
     * @return 美化后的JSON字符串
     */
    public static String prettyJson(String jsonStr) {
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(SerializationFeature.INDENT_OUTPUT);
            Object jsonObject = mapper.readValue(jsonStr, Object.class);
            return mapper.writeValueAsString(jsonObject);
        } catch (Exception e) {
            throw new RuntimeException("Failed to format JSON string: " + e.getMessage(), e);
        }
    }

    /**
     * 美化XML字符串，添加缩进和换行
     *
     * @param xmlStr 原始XML字符串
     * @return 美化后的XML字符串
     */
    public static String prettyXml(String xmlStr) {
        try {
            DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
            DocumentBuilder builder = factory.newDocumentBuilder();
            Document document = builder.parse(new InputSource(new StringReader(xmlStr)));

            TransformerFactory transformerFactory = TransformerFactory.newInstance();
            Transformer transformer = transformerFactory.newTransformer();
            transformer.setOutputProperty(OutputKeys.INDENT, "yes");
            transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
            transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "no");

            StringWriter writer = new StringWriter();
            transformer.transform(new DOMSource(document), new StreamResult(writer));
            return writer.toString();
        } catch (Exception e) {
            throw new RuntimeException("Failed to format XML string: " + e.getMessage(), e);
        }
    }
}
